package com.jeeplus.modules.monitor.task;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.log.ThrottledSlf4jLogger;
import com.jeeplus.modules.api.OrderNumPrefix;
import com.jeeplus.modules.api.utils.PddUtils;
import com.jeeplus.modules.api.utils.WohuiEntity;
import com.jeeplus.modules.api.utils.WohuiUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.ThreadContext;
import org.quartz.DisallowConcurrentExecution;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.SpringContextHolder;
import com.jeeplus.common.utils.net.HttpClientUtil;
import com.jeeplus.modules.api.service.ApiService;
import com.jeeplus.modules.api.utils.MiaoyouquanUtils;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import com.jeeplus.modules.monitor.entity.Task;
import com.jeeplus.modules.taokeorder.entity.TTaokeOrder;
import com.jeeplus.modules.taokeorder.service.TTaokeOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@DisallowConcurrentExecution  
public class TestTask extends Task {
	private static MemberService memberService = SpringContextHolder.getBean(MemberService.class);
	private static TTaokeOrderService tTaokeOrderService = SpringContextHolder.getBean(TTaokeOrderService.class);
	private static ApiService apiService = SpringContextHolder.getBean(ApiService.class);
	
	private static final org.apache.shiro.mgt.SecurityManager MANAGER = SpringContextHolder
			.getBean(org.apache.shiro.mgt.SecurityManager.class);
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public void run() {
		System.out.println("每20分钟查询一次淘客订单。");
		if (ThreadContext.getSecurityManager() == null) {
			ThreadContext.bind(MANAGER);
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Integer page_no = 1;
		String position_index = "";
		// 开始时间
		Date now = new Date();
		String startTime = sdf.format(new Date(now.getTime() - 1200000)); // 10分钟前的时间;
		String endTime = sdf.format(now);
		// 结束时间
		while (true) {
			Map<String, String> params = Maps.newHashMap();
			params.put("sid", "22375");// 对应的淘客账号授权ID
			try {
				params.put("start_time", URLEncoder.encode(startTime,"utf-8"));// 订单查询开始时间，2019-04-05 12:18:22
				params.put("end_time", URLEncoder.encode(endTime,"utf-8"));// 订单查询结束时间，2019-04-25
												// 15:18:22，目前最大可查3个小时内的数据
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
			params.put("page_no", page_no.toString());// 第几页，默认1，1~100
			params.put("page_size", "10");// 页大小，默认20，1~100
//			params.put("member_type", "2");// 推广者角色类型,2:二方，3:三方，不传，表示所有角色
			params.put("order_scene", "2");// 场景订单场景类型，1:常规订单，2:渠道订单，3:会员运营订单，默认为1
			params.put("signurl", "1");// 页大小，默认20，1~100
			if (StringUtils.isNotBlank(position_index)) {
				params.put("position_index", position_index);// 位点，除第一页之外，都需要传递；前端原样返回。注意：从第二页开始，位点必须传递前一页返回的值，否则翻页无效。
				params.put("jump_type", "1");// 跳转类型，当向前或者向后翻页必须提供,-1:
												// 向前翻页,1：向后翻页。
			}
			JSONObject jsonObject = MiaoyouquanUtils.zetaokeAPI(MiaoyouquanUtils.open_dingdanchaxun2, params);
			System.out.println("折淘客返回数据：" + jsonObject.toString());
			JSONObject result = JSONObject.parseObject(HttpClientUtil.doGet(jsonObject.getString("url")));
			if(result==null){
				continue;
			}
			if (result.containsKey("error_response")){
				JSONObject errorResponse=result.getJSONObject("error_response");
				if(errorResponse!=null && "3001".equals(errorResponse.getString("sub_code"))){
					try {
						Thread.sleep(1000);//设置暂停的时间 1 秒
						continue;
					} catch (InterruptedException e2) {
						e2.printStackTrace();
					}
				}
			}
			if (result != null && StringUtils.isNotBlank(result.getString("tbk_sc_order_details_get_response"))) {
				JSONObject dataObject = result.getJSONObject("tbk_sc_order_details_get_response").getJSONObject("data");
				if (dataObject != null) {
					JSONObject results = JSONObject.parseObject(dataObject.getString("results"));
					if (results != null) {
						JSONArray orderArr = results.getJSONArray("publisher_order_dto");
						if (orderArr != null) {
							for (int i = 0; i < orderArr.size(); i++) {
								JSONObject o = orderArr.getJSONObject(i);
								TTaokeOrder taokeOrder = tTaokeOrderService.get(o.getString("trade_id"));
								if(taokeOrder!=null){
									continue;//不为空就跳转
								}
								taokeOrder = new TTaokeOrder();//清空
								taokeOrder.setIsNewRecord(true);
								taokeOrder.setType("0");
								taokeOrder.setId(o.getString("trade_id"));
								// 根据relation_id查询用户
								Member member = memberService.findUniqueByProperty("relation_id",
										o.getString("relation_id"));
								if (member != null) {
									taokeOrder.setMember(member);
								}
								taokeOrder.setAlipayTotalPrice(o.getString("alipay_total_price"));
								taokeOrder.setItemTitle(o.getString("item_title"));
								taokeOrder.setItemImg(o.getString("item_img"));
								taokeOrder.setItemNum(o.getInteger("item_num"));
								taokeOrder.setTradeParentId(o.getString("trade_parent_id"));
								taokeOrder.setTkStatus(o.getString("tk_status"));
								taokeOrder.setItemPrice(o.getString("item_price"));
								taokeOrder.setItemId(o.getString("item_id"));
								taokeOrder.setPubSharePreFee(o.getString("pub_share_pre_fee"));
								String commission_fee="";
								if("饿了么".equals(o.getString("order_type"))){
									float   total_commission_fee =   Float.parseFloat(o.getString("total_commission_fee"));
									float   subsidy_fee   =   Float.parseFloat(o.getString("subsidy_fee"));
									float   zmoney   =     subsidy_fee+total_commission_fee;
									commission_fee  =  Float.toString(zmoney);
								}else{
									commission_fee=o.getString("total_commission_fee");
								}
								taokeOrder.setTotalCommissionFee(commission_fee);
								taokeOrder.setIsJs("0");
								try {
									taokeOrder.setTbPaidTime(StringUtils.isNotBlank(o.getString("tb_paid_time"))
											? sdf.parse(o.getString("tb_paid_time")) : null);
									taokeOrder.setTkCreateTime(StringUtils.isNotBlank(o.getString("tk_create_time"))
											? sdf.parse(o.getString("tk_create_time")) : null);
									tTaokeOrderService.save(taokeOrder);
									//时间转换开始
									SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
									Date date = simpleDateFormat.parse(o.getString("tk_create_time"));
									long ts = date.getTime();
									Date current=simpleDateFormat.parse("2020-06-01 00:00:00");
									long currents = current.getTime();
									//时间转换结束
									String fl;
									if(ts>=currents){
										 fl="0.3";
									}else{
										 fl="0.35";
									}
									//费率
									//类型
									String taobaoSource="";
									if("饿了么".equals(o.getString("order_type"))){
										taobaoSource="ELEME";
									}else if("阿里".equals(o.getString("order_type"))){
										taobaoSource="ALI";
									}else if("淘宝".equals(o.getString("order_type"))){
										taobaoSource="TAOBAO";
									}else if("天猫".equals(o.getString("order_type"))){
										taobaoSource="TMALL";
									}else if("天猫国际".equals(o.getString("order_type"))){
										taobaoSource="TMALLHK";
									}else if("聚划算".equals(o.getString("order_type"))){
										taobaoSource="JHS";
									}else if("".equals(taobaoSource)){
										taobaoSource="ALI";
									}
									//类型end
									if(StringUtils.isNotBlank(taokeOrder.getId())){
										if(member!=null){
											TTaokeOrder to=tTaokeOrderService.get(taokeOrder.getId());
											if(to==null){
												continue;
											}
											if("12".equals(to.getTkStatus())){
												logger.error("淘宝支付订单号"+taokeOrder.getId());
												JSONObject object = apiService.UnionOrderPay(String.valueOf(taokeOrder.getItemNum()),to.getId(), member.getId(), member.getProvince(), member.getCity(), member.getArea(),  to.getAlipayTotalPrice(), (new BigDecimal(to.getPubSharePreFee()).multiply(new BigDecimal(fl)).setScale(2, BigDecimal.ROUND_DOWN)).toString(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(to.getTbPaidTime()), DateUtils.getDateTime(),  taobaoSource,  taokeOrder.getItemId(),taokeOrder.getItemTitle());
												if (!"0000".equals(object.getString("respCode"))) {
													System.out.println("我惠会员系统订单支付失败：" + object.getString("respMsg"));
													logger.error("我惠会员系统请求支付订单失败：" + object.getString("respMsg")+"淘宝支付订单号"+taokeOrder.getId());
												}
											}else if("3".equals(to.getTkStatus())){
												logger.error("淘宝支付订单号"+taokeOrder.getId());

												JSONObject object = apiService.UnionOrderPay(String.valueOf(taokeOrder.getItemNum()),to.getId(), member.getId(), member.getProvince(), member.getCity(), member.getArea(),  to.getAlipayTotalPrice(), (new BigDecimal(to.getPubSharePreFee()).multiply(new BigDecimal(fl)).setScale(2, BigDecimal.ROUND_DOWN)).toString(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(to.getTbPaidTime()), DateUtils.getDateTime(),  taobaoSource,  taokeOrder.getItemId(),taokeOrder.getItemTitle());
												if (!"0000".equals(object.getString("respCode"))) {
													System.out.println("我惠会员系统订单支付失败：" + object.getString("respMsg"));
													logger.error("我惠会员系统请求支付订单失败：" + object.getString("respMsg")+"淘宝支付订单号"+taokeOrder.getId());

												}
												// 用户加铜板
												memberService.updatePoint(to.getMember(), (new BigDecimal(to.getTotalCommissionFee()).multiply(new BigDecimal(fl)).setScale(2, BigDecimal.ROUND_DOWN)).toString(), "1");

												// 调用三方会员系统
												//object = apiService.UnionOrderSettle(to.getId(), to.getAlipayTotalPrice(), to.getTotalCommissionFee());
												logger.error("淘宝结算订单号"+taokeOrder.getId());

												object = apiService.UnionOrderSettle(to.getId(), to.getAlipayTotalPrice(), (new BigDecimal(to.getTotalCommissionFee()).multiply(new BigDecimal(fl)).setScale(2, BigDecimal.ROUND_DOWN)).toString());
												if (!"0000".equals(object.getString("respCode"))) {
													System.out.println("我惠会员系统请求结算订单失败：" + object.getString("respMsg"));
													logger.error("我惠会员系统请求结算订单失败：" + object.getString("respMsg")+"淘宝结算订单号"+taokeOrder.getId());

												}
												to.setIsJs("1");
												tTaokeOrderService.save(to);
											}else if("13".equals(o.getString("tk_status"))){
												// 调用三方失效订单
												logger.error("淘宝取消订单号"+taokeOrder.getId());
												JSONObject object = apiService.UnionOrderInvalid(taokeOrder.getId());
												if (!"0000".equals(object.getString("respCode"))) {
													System.out.println("我惠会员系统请求失效订单失败：" + object.getString("respMsg"));
													logger.error("我惠会员系统请求取消订单失败：" + object.getString("respMsg")+"淘宝取消订单号"+taokeOrder.getId());
												}
											}
										}else{
											logger.info("申请支付失败会员信息", member,"淘宝订单信息",taokeOrder);//
										}
									}
								} catch (ParseException e) {
									e.printStackTrace();
								}
							}
						}
					}
					boolean has_next = dataObject.getBoolean("has_next");
					if (has_next) {
						page_no = page_no + 1;
						position_index = dataObject.getString("position_index");
					} else {
						break;
					}
				}
			}else{
				break;
			}
		}

		// 拼多多订单
		/*Long start_update_time = 1577090453L; // 10分钟前的时间;
		Long end_update_time = 1577091053L;//结束订单
*/		Long start_update_time = now.getTime()/1000 - 1200; // 10分钟前的时间;
		Long end_update_time = now.getTime()/1000;//结束订单
		Map<String, String> params = Maps.newHashMap();
		Integer pageNos = 1;
		params.put("start_update_time", start_update_time.toString());// 订单开始时间
		params.put("end_update_time", end_update_time.toString());// 订单结束时间
		params.put("page", pageNos.toString());// 第几页，默认1，1~100
		params.put("page_size", "100");// 页大小，默认20，1~100
		params.put("query_order_type", "1");// 默认推广订单
		JSONObject jsonObject = PddUtils.duoduorouterAPI(PddUtils.router,PddUtils.getincrementorderlist, params);
		System.out.println("拼多多官方返回数据：" + jsonObject.toString());
		if (jsonObject.containsKey("order_list_get_response")) {
			JSONObject dataObject = jsonObject.getJSONObject("order_list_get_response");
			if(dataObject!=null){
				JSONArray orderList=dataObject.getJSONArray("order_list");
				if(orderList!=null && orderList.size()>0){
					for (int i = 0; i < orderList.size(); i++) {
						JSONObject o = orderList.getJSONObject(i);
						TTaokeOrder to = tTaokeOrderService.get(o.getString("order_sn"));
						if(to!=null){
							if(!to.getTkStatus().equals(o.getString("order_status"))){
								to.setTkStatus(o.getString("order_status"));
								to.setPubSharePreFee((o.getDouble("promotion_amount")/100)+"");
								to.setTotalCommissionFee((o.getDouble("promotion_amount")/100)+"");
								tTaokeOrderService.save(to);
								if(to.getMember()!=null && StringUtils.isNotBlank(to.getMember().getId())){
									if("5".equals(o.getString("order_status")) && "0".equals(to.getIsJs())){
										// 用户加铜板
										memberService.updatePoint(to.getMember(), (new BigDecimal(to.getTotalCommissionFee()).multiply(new BigDecimal("0.35")).setScale(2, BigDecimal.ROUND_DOWN)).toString(), "1");
										// 调用三方会员系统
										logger.error("拼多多结算订单号"+to.getId());

										//JSONObject object = apiService.UnionOrderSettle(to.getId(), to.getAlipayTotalPrice(), to.getTotalCommissionFee());
										JSONObject object = apiService.UnionOrderSettle(to.getId(), to.getAlipayTotalPrice(), (new BigDecimal(to.getTotalCommissionFee()).multiply(new BigDecimal("0.35")).setScale(2, BigDecimal.ROUND_DOWN)).toString());
										if (!"0000".equals(object.getString("respCode"))) {
											System.out.println("我惠会员系统请求结算订单失败：" + object.getString("respMsg"));
											logger.error("我惠会员系统请求结算订单失败：" + object.getString("respMsg")+"拼多多结算订单号"+to.getId());
										}
										to.setIsJs("1");
										tTaokeOrderService.save(to);
									}else if("4".equals(o.getString("order_status"))||"10".equals(o.getString("order_status"))){
										//取消订单
										List<WohuiEntity> list = Lists.newArrayList();
										list.add(new WohuiEntity("OrderNO", to.getId()));
										logger.error("拼多多取消订单号"+to.getId());
										JSONObject object = WohuiUtils.send(WohuiUtils.OrderInvalid, list);
										if (!"0000".equals(object.getString("respCode"))) {

											System.out.println("取消订单号"+to.getId()+"失败：" + object.getString("respMsg"));
											logger.error("取消订单号"+to.getId()+"失败：" + object.getString("respMsg")+"拼多多取消订单号"+to.getId());
										}
									}
								}
							}
						}else{
							TTaokeOrder taokeOrder = new TTaokeOrder();
							taokeOrder.setIsNewRecord(true);
							taokeOrder.setType("1");
							taokeOrder.setId(o.getString("order_sn"));
							// 根据推广位ID查询用户
							Member member = memberService.findUniqueByProperty("pdd_id",
									o.getString("p_id"));
							if (member != null) {
								taokeOrder.setMember(member);
							}
							taokeOrder.setAlipayTotalPrice((o.getDouble("order_amount")/100)+"");
							taokeOrder.setItemTitle(o.getString("goods_name"));
							taokeOrder.setItemImg(o.getString("goods_thumbnail_url"));
							taokeOrder.setItemNum(o.getInteger("goods_quantity"));
							taokeOrder.setTradeParentId(o.getString("order_sn"));
							taokeOrder.setTkStatus(o.getString("order_status"));
							taokeOrder.setItemPrice((o.getDouble("goods_price")/100)+"");
							taokeOrder.setItemId(o.getString("goods_id"));
							taokeOrder.setPubSharePreFee((o.getDouble("promotion_amount")/100)+"");
							taokeOrder.setTotalCommissionFee((o.getDouble("promotion_amount")/100)+"");
							taokeOrder.setTbPaidTime(StringUtils.isNotBlank(o.getString("order_pay_time"))
									? new Date(o.getLong("order_pay_time")*1000) : null);
							taokeOrder.setTkCreateTime(StringUtils.isNotBlank(o.getString("order_create_time"))
									? new Date(o.getLong("order_create_time")*1000) : null);
							taokeOrder.setIsJs("0");
							taokeOrder.setGoodsSign(o.getString("goods_sign"));
							tTaokeOrderService.save(taokeOrder);
							if(StringUtils.isNotBlank(taokeOrder.getId())){
								if(taokeOrder.getMember()!=null && StringUtils.isNotBlank(taokeOrder.getMember().getId())){
									to=tTaokeOrderService.get(taokeOrder.getId());
									if(to==null){
										continue;
									}
									if("0".equals(to.getTkStatus()) || "1".equals(to.getTkStatus()) || "8".equals(to.getTkStatus())){
										logger.error("拼多多支付订单号"+to.getId());

										JSONObject object = apiService.UnionOrderPay(String.valueOf(taokeOrder.getItemNum()),to.getId(), member.getId(), member.getProvince(), member.getCity(), member.getArea(),  to.getAlipayTotalPrice(), (new BigDecimal(to.getPubSharePreFee()).multiply(new BigDecimal("0.35")).setScale(2, BigDecimal.ROUND_DOWN)).toString(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(to.getTbPaidTime()), DateUtils.getDateTime(),  "PDD",  taokeOrder.getItemId(), taokeOrder.getItemTitle());
										if (!"0000".equals(object.getString("respCode"))) {
											System.out.println("我惠会员系统订单支付失败：" + object.getString("respMsg"));
											logger.error("我惠会员系统订单支付失败：" + object.getString("respMsg")+"拼多多支付订单号"+to.getId());

										}
									}else if("5".equals(to.getTkStatus())){
										logger.error("拼多多支付订单号"+to.getId());

										JSONObject object = apiService.UnionOrderPay(String.valueOf(taokeOrder.getItemNum()),to.getId(), member.getId(), member.getProvince(), member.getCity(), member.getArea(),  to.getAlipayTotalPrice(), (new BigDecimal(to.getPubSharePreFee()).multiply(new BigDecimal("0.35")).setScale(2, BigDecimal.ROUND_DOWN)).toString(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(to.getTbPaidTime()), DateUtils.getDateTime(),  "PDD", taokeOrder.getItemId(), taokeOrder.getItemTitle());
										if (!"0000".equals(object.getString("respCode"))) {
											System.out.println("我惠会员系统订单支付失败：" + object.getString("respMsg"));
											logger.error("我惠会员系统订单支付失败：" + object.getString("respMsg")+"拼多多支付订单号"+to.getId());

										}
										
										// 用户加铜板
										memberService.updatePoint(to.getMember(), (new BigDecimal(to.getTotalCommissionFee()).multiply(new BigDecimal("0.35")).setScale(2, BigDecimal.ROUND_DOWN)).toString(), "1");
										
										// 调用三方会员系统
										logger.error("拼多多结算订单号"+to.getId());

										//object = apiService.UnionOrderSettle(to.getId(), to.getAlipayTotalPrice(), to.getTotalCommissionFee());
										object = apiService.UnionOrderSettle(to.getId(), to.getAlipayTotalPrice(), (new BigDecimal(to.getTotalCommissionFee()).multiply(new BigDecimal("0.35")).setScale(2, BigDecimal.ROUND_DOWN)).toString());
										if (!"0000".equals(object.getString("respCode"))) {
											System.out.println("我惠会员系统请求结算订单失败：" + object.getString("respMsg"));
											logger.error("我惠会员系统订单结算失败：" + object.getString("respMsg")+"拼多多结算订单号"+to.getId());

										}
										to.setIsJs("1");
										tTaokeOrderService.save(to);
									}else if("4".equals(to.getTkStatus())||"10".equals(to.getTkStatus())){
										//取消订单
										List<WohuiEntity> list = Lists.newArrayList();
										list.add(new WohuiEntity("OrderNO", to.getId()));
										logger.error("拼多多取消订单号"+to.getId());
										JSONObject object = WohuiUtils.send(WohuiUtils.OrderInvalid, list);
										if (!"0000".equals(object.getString("respCode"))) {
											System.out.println("取消订单号"+to.getId()+"失败：" + object.getString("respMsg"));
											logger.error("取消订单号"+to.getId()+"失败：" + object.getString("respMsg")+"拼多多取消订单号"+to.getId());
										}
									}else{
									logger.info("申请支付失败会员信息", taokeOrder.getMember(),"拼多多订单信息",taokeOrder);//
								}
							}
						}
					}
				}
			}
		}
		}

		//京东订单
		Integer pageNo = 1;
		Calendar beforeTime = Calendar.getInstance();
		beforeTime.add(Calendar.MINUTE, -20);// 10分钟之前的时间
		Date beforeD = beforeTime.getTime();
		String before10 = new SimpleDateFormat("yyyyMMddHH").format(beforeD);  // 前十分钟时间
		//String before10 = "2019112309";  // 前十分钟时间
		while(true) {
			Map<String, String> jdparams = Maps.newHashMap();
			jdparams.put("time", before10);// 查询时间，建议使用分钟级查询，格式：yyyyMMddHH、yyyyMMddHHmm或yyyyMMddHHmmss，如201811031212 的查询范围从12:12:00--12:12:59
			jdparams.put("type", "1");// 订单时间查询类型(1：下单时间，2：完成时间，3：更新时间)
			jdparams.put("pageNo", pageNo.toString());// 第几页
			jdparams.put("pageSize", "100");// 订单结束时间
			jdparams.put("key_id", MiaoyouquanUtils.lmdykey);// 京东联盟授权key
			JSONObject jdObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.getJdUnionOrders, jdparams);
			System.out.println("京东喵有券返回数据：" + jdObject.toString());
			if (jdObject.containsKey("code")&&"200".equals(jdObject.getString("code"))) {
				JSONObject dataObject=jdObject.getJSONObject("data");
				if(dataObject!=null){
					JSONArray orderList=dataObject.getJSONArray("list");
					if(orderList!=null && orderList.size()>0){
						for (int i = 0; i < orderList.size(); i++) {
							JSONObject o = orderList.getJSONObject(i);
							TTaokeOrder taokeOrder=new TTaokeOrder();
							taokeOrder.setTradeParentId(o.getString("orderId"));
							List<TTaokeOrder> oList=tTaokeOrderService.findList(taokeOrder);
							if(oList!=null && oList.size()>0){
								for(int j = 0; j < oList.size(); j++){
									JSONArray dataArray=o.getJSONArray("skuList");
									if(dataArray!=null && dataArray.size()>0){
										for(int m = 0; m<dataArray.size();m++){
											JSONObject sku = dataArray.getJSONObject(m);
											if(oList.get(j).getItemId().equals(sku.getString("skuId"))){
												/*oList.get(j).setTkStatus(sku.getString("validCode"));*/
												if(!"15".equals(sku.getString("validCode")) && !"16".equals(sku.getString("validCode")) && !"17".equals(sku.getString("validCode")) && !"18".equals(sku.getString("validCode"))){
													oList.get(j).setTkStatus("20");
													//取消订单
													List<WohuiEntity> list = Lists.newArrayList();
													list.add(new WohuiEntity("OrderNO", oList.get(j).getId()));
													logger.error("京东取消订单号"+oList.get(j).getId());
													JSONObject object = WohuiUtils.send(WohuiUtils.OrderInvalid, list);
													if (!"0000".equals(object.getString("respCode"))) {

														System.out.println("取消订单号"+oList.get(j).getId()+"失败：" + object.getString("respMsg"));
														logger.error("取消订单号"+oList.get(j).getId()+"失败：" + object.getString("respMsg")+"京东取消订单号"+oList.get(j).getId());

													}
												}else{
													oList.get(j).setTkStatus(sku.getString("validCode"));
												}
												taokeOrder.setPubSharePreFee(sku.getString("estimateFee"));
												oList.get(j).setTotalCommissionFee(sku.getString("actualFee"));
												tTaokeOrderService.save(oList.get(j));
												if(oList.get(j).getMember()!=null && StringUtils.isNotBlank(oList.get(j).getMember().getId())){
													if("17".equals(oList.get(j).getTkStatus()) && "0".equals(oList.get(j).getIsJs())){
														// 用户加铜板
														memberService.updatePoint(oList.get(j).getMember(), (new BigDecimal(oList.get(j).getTotalCommissionFee()).multiply(new BigDecimal("0.35")).setScale(2, BigDecimal.ROUND_DOWN)).toString(), "1");
														logger.error("京东结算订单号"+oList.get(j).getId());

														// 调用三方会员系统
														//JSONObject object = apiService.UnionOrderSettle(oList.get(j).getId(), oList.get(j).getAlipayTotalPrice(), oList.get(j).getTotalCommissionFee());
														JSONObject object = apiService.UnionOrderSettle(oList.get(j).getId(), oList.get(j).getAlipayTotalPrice(), (new BigDecimal(oList.get(j).getTotalCommissionFee()).multiply(new BigDecimal("0.35")).setScale(2, BigDecimal.ROUND_DOWN)).toString());
														if (!"0000".equals(object.getString("respCode"))) {
															System.out.println("我惠会员系统请求结算订单失败：" + object.getString("respMsg"));
															logger.error("我惠会员系统订单结算失败：" + object.getString("respMsg")+"京东结算订单号"+oList.get(j).getId());

														}
														oList.get(j).setIsJs("1");
														tTaokeOrderService.save(oList.get(j));
													}
												}
											}
										}
									}
								}
							}else{
								//商品规格列表
								JSONArray dataArray=o.getJSONArray("skuList");
								if(dataArray!=null && dataArray.size()>0){
									for(int j = 0; j < dataArray.size(); j++){
										JSONObject sku = dataArray.getJSONObject(j);
										taokeOrder = new TTaokeOrder();
										taokeOrder.setIsNewRecord(true);
										taokeOrder.setType("2");
										taokeOrder.setId(o.getString("orderId")+j);
										// 根据推广位ID查询用户
										Member member = memberService.findUniqueByProperty("jd_id",
												sku.getString("positionId"));
										if (member != null) {
											taokeOrder.setMember(member);
										}
										taokeOrder.setItemTitle(sku.getString("skuName"));
										//根据商品ID查询商品图片
										params = Maps.newHashMap();
										params.put("skuid", sku.getString("skuId"));
										JSONObject infoObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.getItemInfo, params);
										if(infoObject!=null){
											JSONArray itemInfoList = infoObject.getJSONObject("data").getJSONArray("ItemInfo");
											if(itemInfoList!=null && itemInfoList.size()>0){
												taokeOrder.setItemImg(itemInfoList.getJSONObject(0).getString("imgUrl"));
											}
										}
										taokeOrder.setItemNum(sku.getInteger("skuNum"));
										taokeOrder.setItemPrice(sku.getString("price"));
										taokeOrder.setItemId(sku.getString("skuId"));
										taokeOrder.setAlipayTotalPrice((new BigDecimal(sku.getString("price")).multiply(new BigDecimal(sku.getString("skuNum")))).toString());
										taokeOrder.setTradeParentId(o.getString("orderId"));
										if(!"15".equals(sku.getString("validCode")) && !"16".equals(sku.getString("validCode")) && !"17".equals(sku.getString("validCode")) && !"18".equals(sku.getString("validCode"))){
											taokeOrder.setTkStatus("20");
										}else{
											taokeOrder.setTkStatus(sku.getString("validCode"));
										}
										taokeOrder.setPubSharePreFee(sku.getString("estimateFee"));
										taokeOrder.setTotalCommissionFee(sku.getString("actualFee"));
										taokeOrder.setTbPaidTime(StringUtils.isNotBlank(o.getString("orderTime"))
												? new Date(o.getLong("orderTime")) : null);
										taokeOrder.setTkCreateTime(StringUtils.isNotBlank(o.getString("orderTime"))
												? new Date(o.getLong("orderTime")) : null);
										taokeOrder.setIsJs("0");
										tTaokeOrderService.save(taokeOrder);
										if (member != null) {
											TTaokeOrder to=tTaokeOrderService.get(taokeOrder.getId());
											if(to!=null && "16".equals(to.getTkStatus())){
												logger.error("京东支付订单号"+to.getId());

												JSONObject object = apiService.UnionOrderPay(String.valueOf(taokeOrder.getItemNum()),to.getId(), member.getId(), member.getProvince(), member.getCity(), member.getArea(),  to.getAlipayTotalPrice(), (new BigDecimal(to.getPubSharePreFee()).multiply(new BigDecimal("0.35")).setScale(2, BigDecimal.ROUND_DOWN)).toString(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(to.getTbPaidTime()), DateUtils.getDateTime(),  "JD",  taokeOrder.getItemId(),taokeOrder.getItemTitle());
												if (!"0000".equals(object.getString("respCode"))) {
													System.out.println("我惠会员系统订单支付失败：" + object.getString("respMsg"));
													logger.error("我惠会员系统订单支付失败：" + object.getString("respMsg")+"京东支付订单号"+to.getId());

												}
											}else if(to!=null && "17".equals(to.getTkStatus())){
												logger.error("京东支付订单号"+to.getId());

												JSONObject object = apiService.UnionOrderPay(String.valueOf(taokeOrder.getItemNum()),to.getId(), member.getId(), member.getProvince(), member.getCity(), member.getArea(),  to.getAlipayTotalPrice(), (new BigDecimal(to.getPubSharePreFee()).multiply(new BigDecimal("0.35")).setScale(2, BigDecimal.ROUND_DOWN)).toString(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(to.getTbPaidTime()), DateUtils.getDateTime(),  "JD",  taokeOrder.getItemId(),taokeOrder.getItemTitle());
												if (!"0000".equals(object.getString("respCode"))) {
													System.out.println("我惠会员系统订单支付失败：" + object.getString("respMsg"));
													logger.error("我惠会员系统订单支付失败：" + object.getString("respMsg")+"京东支付订单号"+to.getId());

												}
												
												// 用户加铜板
												memberService.updatePoint(to.getMember(), (new BigDecimal(to.getTotalCommissionFee()).multiply(new BigDecimal("0.35")).setScale(2, BigDecimal.ROUND_DOWN)).toString(), "1");
												
												// 调用三方会员系统
												logger.error("京东结算订单号"+oList.get(j).getId());

												//object = apiService.UnionOrderSettle(to.getId(), to.getAlipayTotalPrice(), to.getTotalCommissionFee());
												object = apiService.UnionOrderSettle(oList.get(j).getId(), oList.get(j).getAlipayTotalPrice(), (new BigDecimal(to.getTotalCommissionFee()).multiply(new BigDecimal("0.35")).setScale(2, BigDecimal.ROUND_DOWN)).toString());
												if (!"0000".equals(object.getString("respCode"))) {
													System.out.println("我惠会员系统请求结算订单失败：" + object.getString("respMsg"));
													logger.error("我惠会员系统订单结算失败：" + object.getString("respMsg")+"京东结算订单号"+oList.get(j).getId());

												}
												to.setIsJs("0");
												tTaokeOrderService.save(to);
											}
										}else{
											logger.info("申请支付失败会员信息", member,"京东订单信息",taokeOrder);//
										}

									}
								}
							}
						}
					}
					boolean has_next = dataObject.getBoolean("hasMore");
					if (has_next) {
						pageNo = pageNo + 1;
					} else {
						break;
					}
				}else{
					break;
				}
			}else{
				break;
			}
		}
	}
}
